package com.tanjie.blackbean.auth.granter;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.tanjie.blackbean.core.util.TokenUtil;
import com.tanjie.blackbean.pojo.auth.*;
import com.tanjie.blackbean.pojo.system.ClientType;
import com.tanjie.blackbean.pojo.system.UserInfoQuery;
import com.tanjie.blackbean.system.admin.feign.IUserClient;
import com.tanjie.blackbean.pojo.exception.BizException;
import com.tanjie.blackbean.pojo.response.AuthErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author: tanjie
 * @date: 2022-04-24
 **/
@Slf4j
@Component
public class PasswordGranter extends AbstractTokenGranter {

    @Resource
    IUserClient userClient;

    @Override
    public GrantType grantType() {
        return GrantType.PASSWORD;
    }

    @Override
    public AuthInfo grant(AuthParam authParam) {
        UsernamePassword usernamePassword = authParam.getUsernamePassword();
        String username = usernamePassword.getUsername();
        String password = usernamePassword.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            throw new BizException(AuthErrorCode.USERNAME_OR_PWD_BLANK);
        }
        // 查询用户
        ClientType clientType = authParam.getClientType();
        UserInfoWithRolesAndPerms userInfo = userClient.queryUser(UserInfoQuery.builder()
                .username(username)
                .password(password)
                .encrypted(false)
                .clientType(clientType)
                .build());
        if (userInfo == null) {
            throw new BizException(AuthErrorCode.USERNAME_OR_PWD_WRONG);
        }
        if (!(userInfo.getStatus() == 1)) {
            throw new BizException(AuthErrorCode.USER_FORBIDDEN);
        }
        // 将用户认证信息保存到Redis中
        DateTime expiresIn = DateUtil.offsetSecond(new Date(), 3600);
        super.saveToCache(userInfo, expiresIn);

        // 创建token和接口返回内容
        String token;
        String refreshToken;
        try {
            token = TokenUtil.createToken(userInfo, expiresIn);
            refreshToken = TokenUtil.createRefreshToken(userInfo.getId());
        } catch (Exception e) {
            throw new BizException(("生成token失败，cause:{}"), e.getMessage());
        }
        return AuthInfo.builder()
                .accessToken(token)
                .refreshToken(refreshToken)
                .username(username)
                .expiresIn(expiresIn.getTime())
                .build();
    }

}













